package com.tuanzi.loan.web.bean.pageTemplate;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.pageTemplate.LoanPageTemplateInfo;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.common.CommProductIdService;
import com.tuanzi.loan.business.service.pageTemplate.LoanPageTemplateInfoService;
import com.tuanzi.loan.business.service.pageTemplate.impl.LoanPageTemplateInfoServiceImpl;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.family.product.LoanApplicationExportView;
import com.tuanzi.loan.vo.view.pageTemplate.LoanPageTemplateInfoView;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @Auther: hequnayu
 * @Date: 2019/9/17 11:28
 * @Description:
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanPageTemplateInfoBean extends JSFInfoBean<LoanPageTemplateInfoView> {

    private static final long serialVersionUID = -9082635336576159213L;
    @Autowired
    private CommProductIdService commProductIdService;
    @Autowired
    private LoanPageTemplateInfoService templateInfoService;
    @Autowired
    private DictionaryService dictionaryService;

    private List<LoanPageTemplateInfoServiceImpl.CommProductVo> products;
    private Set<String> canSelectProducts;
    private Integer dbUserType;
    private List<LoanPageTemplateInfoView.ModuleItem> dbUserModuleItems;
    private String userTypeName;
    private String parentProdName;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = templateInfoService.loadPageTemplateInfoView(Long.parseLong(id));
            dbUserType = $.getUserType();
            dbUserModuleItems = new ArrayList<>();
            dbUserModuleItems.addAll($.getShowUserModuleItems());
            Dictionary parentProd = dictionaryService.findByCodeAndValue1("LARGE_COMMON_PRODUCT", $.getParentId());
            if (parentProd != null){
                parentProdName = parentProd.getName();
            }
            if ($.getUserType() == null){
                userTypeName = "";
            }else{
                findUserTypeName($.getUserType().toString());
            }
            onSelectParentProd();
        } else {
            $ = new LoanPageTemplateInfoView();
            $.setSubstitute(false);
            onAddModule();
            changeStatusToAdd();
        }
    }

    public void onSelectParentProd(){
        if (!StringUtils.isEmpty($.getParentId())){
            products = templateInfoService.getProducts(commProductIdService.findAllByParentId($.getParentId()),$.getId());
        }else{
            products = templateInfoService.getProducts(commProductIdService.findAll(),$.getId());
        }
        Dictionary parentProd = dictionaryService.findByCodeAndValue1("LARGE_COMMON_PRODUCT", $.getParentId());
        if (parentProd != null){
            parentProdName = parentProd.getName();
        }
    }

    public void onSelectAllProduct() {
        canSelectProducts = products.stream().filter(p -> !p.isHadSet()).map(product -> product.getProductId().toString()).collect(Collectors.toSet());
        if (org.apache.commons.collections.CollectionUtils.isEmpty($.getSelectedOnlineProducts()) || $.getSelectedOnlineProducts().size() < canSelectProducts.size()) {
            $.setSelectedOnlineProducts(canSelectProducts);
        } else {
            $.getSelectedOnlineProducts().clear();
        }
    }


    public void onAddModule(){
        LoanPageTemplateInfoView.ModuleItem moduleItem = new LoanPageTemplateInfoView.ModuleItem();
        moduleItem.setUserType(-1);
        $.getGloablModuleItems().add(moduleItem);
    }

    public void onDeleteModule(int index){
        $.getGloablModuleItems().remove(index);
    }

    //选择为对应用户添加模板
    public void onSelectUserType(){

        if (CollectionUtils.isNotEmpty($.getShowUserModuleItems())){
            $.getShowUserModuleItems().clear();
        }
        if ($.getUserType() != null && dbUserType == $.getUserType()){
            $.getShowUserModuleItems().addAll(dbUserModuleItems);
        }else{
            LoanPageTemplateInfoView.ModuleItem moduleItem = new LoanPageTemplateInfoView.ModuleItem();
            moduleItem.setUserType($.getUserType());
            $.getShowUserModuleItems().add(moduleItem);
        }

        if ($.getUserType() == null){
            userTypeName = "";
        }else{
            findUserTypeName($.getUserType().toString());
        }
    }

    public void findUserTypeName(String userType){
        Dictionary page_template_user_type = dictionaryService.findByCodeAndValue1("PAGE_TEMPLATE_USER_TYPE", userType);
        if (page_template_user_type != null){
            userTypeName = page_template_user_type.getName();
        }
    }

    //对应用户添加模块
    public void onAddUserModule(){
        LoanPageTemplateInfoView.ModuleItem moduleItem = new LoanPageTemplateInfoView.ModuleItem();
        moduleItem.setUserType($.getUserType());
        $.getShowUserModuleItems().add(moduleItem);
    }

    public void onDeleteUserModule(int index){
        $.getShowUserModuleItems().remove(index);
    }

    public void onSave(){
        if (!validate()){
            return;
        }
        setModuleItem($.getGloablModuleItems());
        setModuleItem($.getShowUserModuleItems());
        if ($.getSubstitute()){  //替补模板不保存大产品跟相关产品，全局通用
            $.setParentId("");
        }
        templateInfoService.savePageTemplate($);
        changeStatusToView();
        addSuccessfullyMessage();
    }

    //获取数据字典配置的分组id和广告位id
    public void setModuleItem(List<LoanPageTemplateInfoView.ModuleItem> items){
        for (int i = 0 ; i < items.size() ; i++){
            LoanPageTemplateInfoView.ModuleItem moduleItem = items.get(i);
            Integer moduleId = moduleItem.getModuleId();
            Dictionary templateModule = dictionaryService.findByCodeAndValue1("PAGE_TEMPLATE_MODULE", moduleId.toString());
            moduleItem.setPosition(i+1);
            if (StringUtils.isNotEmpty(templateModule.getValue2())){
                moduleItem.setGroupId(Integer.parseInt(templateModule.getValue2()));
            }else{
                moduleItem.setGroupId(null);
            }
            if (StringUtils.isNotEmpty(templateModule.getValue3())){
                moduleItem.setSpaceId(Integer.parseInt(templateModule.getValue3()));
            }else{
                moduleItem.setSpaceId(null);
            }

            if (1 != moduleItem.getShowTitle()){
                moduleItem.setTitle(null);
            }
        }
    }

    public void onCopyPageTemplate(){
        $.setId(null);
        $.setStatus(0);
        $.setName("");
        $.setParentId("");
        $.setSelectedOnlineProducts(null);
        onSelectParentProd();
        changeStatusToEdit();
    }

    public boolean validate(){
        if (StringUtils.isEmpty($.getName())){
            addErrorMessage("请输入模板名称！");
            return false;
        }
        if ($.getSubstitute()){
            List<LoanPageTemplateInfo> substitutes = templateInfoService.findSubstitute();
            if (CollectionUtils.isNotEmpty(substitutes) && $.getId() != substitutes.get(0).getId()){
                addErrorMessage("已经有替补模板，不能重复添加！");
                return false;
            }
        }else{ //非替补模板必选产品
            if (StringUtils.isEmpty($.getParentId())){
                addErrorMessage("请选择适用大产品！");
                return false;
            }else{
                if (CollectionUtils.isEmpty($.getSelectedOnlineProducts())){
                    addErrorMessage("请选择适用产品！");
                    return false;
                }
            }
        }

        //校验通用模板配置
        if (CollectionUtils.isEmpty($.getGloablModuleItems())){
            addErrorMessage("请配置通用模板！");
            return false;
        }else{
            if ($.getGloablModuleItems().size() < 3){
                addErrorMessage("通用模板配置最少需要3个模块！");
                return false;
            }else{
                List<LoanPageTemplateInfoView.ModuleItem> gloablModuleItems = $.getGloablModuleItems();
                int i;
                for (i = 0;i<gloablModuleItems.size();i++){
                    LoanPageTemplateInfoView.ModuleItem moduleItem = gloablModuleItems.get(i);
                    if (moduleItem.getModuleId() == null){
                        addErrorMessage("请选择模块顺序"+(i+1)+"展示模块");
                        break;
                    }
                    if (moduleItem.getShowTitle() == null){
                        addErrorMessage("请选择模块顺序"+(i+1)+"是否带标题");
                        break;
                    }else{
                        if (moduleItem.getShowTitle() == 1){
                            if (StringUtils.isEmpty(moduleItem.getTitle())){
                                addErrorMessage("请选择模块顺序"+(i+1)+"标题名称");
                                break;
                            }
                        }
                    }
                }
                if (i != gloablModuleItems.size()){
                    return false;
                }
            }
        }

        //校验对应用户模板配置
        if (null != $.getUserType()){
            if ($.getShowUserModuleItems().size() < 3){
                addErrorMessage("对应用户模板配置最少需要3个模块！");
                return false;
            }else{
                List<LoanPageTemplateInfoView.ModuleItem> showUserModuleItems = $.getShowUserModuleItems();
                int j;
                for (j = 0;j<showUserModuleItems.size();j++){
                    LoanPageTemplateInfoView.ModuleItem moduleItem = showUserModuleItems.get(j);
                    if (moduleItem.getModuleId() == null){
                        addErrorMessage("请选择模块顺序"+(j+1)+"展示模块");
                        break;
                    }
                    if (moduleItem.getShowTitle() == null){
                        addErrorMessage("请选择模块顺序"+(j+1)+"是否带标题");
                        break;
                    }else{
                        if (moduleItem.getShowTitle() == 1){
                            if (StringUtils.isEmpty(moduleItem.getTitle())){
                                addErrorMessage("请选择模块顺序"+(j+1)+"标题名称");
                                break;
                            }
                        }
                    }
                }
                if (j != showUserModuleItems.size()){
                    return false;
                }
            }
        }
        return true;
    }

//    public void onSelectSubstitute(){
//        $.setParentId("");
//        if (CollectionUtils.isNotEmpty($.getSelectedOnlineProducts())){
//            $.getSelectedOnlineProducts().clear();
//        }
//    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(LARGE_COMMON_PRODUCT,ONLINE_OFFLINE_STATUS,PAGE_TEMPLATE_MODULE,PAGE_TEMPLATE_USER_TYPE);
    }

}
